


//
//  LYRechargeController.m
//  SelectCity
//
//  Created by liuyan on 2019/3/30.
//  Copyright © 2019年 liuyan. All rights reserved.
//

#import "LYRechargeController.h"
#import "LYResumePayTypeCell.h"
#import "LYResumePaytypeModel.h"

@interface LYRechargeController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger payIndex;
@property (nonatomic, strong) UITextField *moneyTF;
@property (nonatomic, strong) UILabel *balanceLabel;

//有小数点
@property (nonatomic, assign) BOOL isHaveDian;
//第一个零
@property (nonatomic, assign) BOOL isFirstZero;

@property (nonatomic, strong) NSDictionary *dataDic;

@end

@implementation LYRechargeController

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSubview];
    [self requestAmountData];
}

- (void)createSubview{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfStatusBarAndNavigationBar) style:UITableViewStyleGrouped];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.showsVerticalScrollIndicator = NO;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = [UIColor whiteColor];
    self.tableview.hidden = YES;
    self.tableview.sectionIndexBackgroundColor = [UIColor clearColor];
    
    [self.tableview registerClass:[LYResumePayTypeCell class] forCellReuseIdentifier:kCellIdentifier_LYResumePayTypeCell];
    [self.view addSubview:self.tableview];
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 136)];
    header.backgroundColor = [UIColor whiteColor];
    self.tableview.tableHeaderView = header;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15,10, WIDTH - 40, 15)];
    titleLabel.text = @"账户余额";
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.adjustsFontSizeToFitWidth = YES;
    titleLabel.textColor = RGB(34, 34, 34);
    [header addSubview:titleLabel];
    
    UILabel *balanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(15,titleLabel.bottom, WIDTH - 40, 35)];
    balanceLabel.font = [UIFont boldSystemFontOfSize:20];
    balanceLabel.adjustsFontSizeToFitWidth = YES;
    self.balanceLabel = balanceLabel;
    balanceLabel.textColor = [UIColor orangeColor];
    [header addSubview:balanceLabel];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(20, balanceLabel.bottom +5, WIDTH - 40, 1)];
    line.backgroundColor = RGB(247, 247, 247);
    [header addSubview:line];
    
    UILabel *inputLabel = [[UILabel alloc] initWithFrame:CGRectMake(15,line.bottom + 5, WIDTH - 40, 15)];
    inputLabel.text = @"请输入充值金额";
    inputLabel.font = [UIFont systemFontOfSize:12];
    inputLabel.adjustsFontSizeToFitWidth = YES;
    inputLabel.textColor = RGB(34, 34, 34);
    [header addSubview:inputLabel];
    
    self.moneyTF = [[UITextField alloc] initWithFrame:CGRectMake(15, inputLabel.bottom+5, WIDTH - 30, 45)];
    self.moneyTF.placeholder = @"请在此输入充值金额";
    self.moneyTF.textColor = RGB(34, 34, 34);
    self.moneyTF.font = [UIFont systemFontOfSize:16];
    self.moneyTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.moneyTF.delegate = self;
    [header addSubview:self.moneyTF];
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 70)];
    self.tableview.tableFooterView = footer;
    
    UIButton *paybutton = [UIButton buttonWithType:UIButtonTypeCustom];
    paybutton.frame = CGRectMake( 40, 15, WIDTH-80, 40);
    paybutton.layer.cornerRadius = paybutton.height/2;
    paybutton.clipsToBounds = YES;
    paybutton.backgroundColor = [UIColor orangeColor];
    [paybutton setTitle:@"立即支付" forState:UIControlStateNormal];
    [paybutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    paybutton.titleLabel.font = [UIFont systemFontOfSize:14];
    [paybutton addTarget:self action:@selector(paybuttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:paybutton];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LYResumePayTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_LYResumePayTypeCell forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LYResumePaytypeModel *model = self.dataArray[indexPath.row];
    if (!model.isSelected) {
        for (LYResumePaytypeModel *paymodel in self.dataArray) {
            if (model == paymodel) {
                paymodel.isSelected = YES;
                self.payIndex = indexPath.row;
            }else{
                paymodel.isSelected = NO;
            }
        }
        [tableView reloadData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 8)];
    view.backgroundColor = RGB(247, 247, 247);
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 8;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001f;
}

#pragma mark --UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.moneyTF) {
        if ([textField.text rangeOfString:@"."].location==NSNotFound) {
            _isHaveDian = NO;
        }
        if ([textField.text rangeOfString:@"0"].location==NSNotFound) {
            _isFirstZero = NO;
        }
        if ([string length]>0){
            unichar single=[string characterAtIndex:0];//当前输入的字符
            if ((single >='0' && single<='9') || single=='.'){//数据格式正确
                if([textField.text length]==0){
                    if(single == '.'){
                        //首字母不能为小数点
                        return NO;
                    }
                    if (single == '0') {
                        _isFirstZero = YES;
                        return YES;
                    }
                }
                
                if (single=='.'){
                    if(!_isHaveDian)//text中还没有小数点
                    {
                        _isHaveDian=YES;
                        return YES;
                    }else{
                        return NO;
                    }
                }else if(single=='0'){
                    if ((_isFirstZero&&_isHaveDian)||(!_isFirstZero&&_isHaveDian)) {
                        //首位有0有.（0.01）或首位没0有.（10200.00）可输入两位数的0
                        if([textField.text isEqualToString:@"0.0"]){
                            return NO;
                        }
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt=(int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if (_isFirstZero&&!_isHaveDian){
                        //首位有0没.不能再输入0
                        return NO;
                    }else{
                        return YES;
                    }
                }else{
                    if (_isHaveDian){
                        //存在小数点，保留两位小数
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt= (int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if(_isFirstZero&&!_isHaveDian){
                        //首位有0没点
                        return NO;
                    }else{
                        return YES;
                    }
                }
            }else{
                //输入的数据格式不正确
                SVPHUDError(@"请输入正确的提现金额");
                return NO;
            }
        }else{
            return YES;
        }
    }
    return YES;
}

#pragma mark -- LoadData
- (void)requestAmountData{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    __weak typeof(self) weakSelf = self;
    [BaseNetManager requestWithMethod:POST path:Wallet_getChargeConfig_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            [weakSelf organizeData:responseObject[@"data"]];
        }else if ([responseObject[@"code"] integerValue] == 1400){
            SVPHUDError(responseObject[@"msg"]);
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}

- (void)organizeData:(NSDictionary *)dataDic{
    self.dataDic = dataDic;
    self.tableview.hidden = NO;
    //钱包信息
    CGFloat amount = [dataDic[@"amount"] floatValue];
    self.balanceLabel.text = [UIToolsControl showAmount:[NSString stringWithFormat:@"%.2f",amount]];
    
    if (self.dataArray.count) {
        LYResumePaytypeModel *model = self.dataArray[0];
        model.isSelected = YES;
    }
    [self.tableview reloadData];
}


#pragma mark -- Action
- (void)paybuttonClick:(UIButton *)button{
    [self.moneyTF resignFirstResponder];
    NSString *money = self.moneyTF.text;
    if (money.length == 0) {
        //请输入金额
        SVPHUDError(@"请输入充值金额");
        return;
    }
    
    if ([money floatValue] <= 0) {
        SVPHUDError(@"充值金额要大于零");
        return;
    }
    
    //最小充值金额
    CGFloat amount_min = [self.dataDic[@"amount_min"] floatValue];
    if ([money floatValue] < amount_min) {
        NSString *message = [NSString stringWithFormat:@"充值金额最少%@",[UIToolsControl showAmount:[NSString stringWithFormat:@"%.2f",amount_min]]];
        SVPHUDError(message);
        return;
    }
    
    //最大充值金额
    CGFloat amount_max = [self.dataDic[@"amount_max"] floatValue];
    if ([money floatValue] > amount_max) {
        NSString *message = [NSString stringWithFormat:@"充值金额最大%@",[UIToolsControl showAmount:[NSString stringWithFormat:@"%.2f",amount_max]]];
        SVPHUDError(message);
        return;
    }
    
    //支付方式
    LYResumePaytypeModel *paymodel = self.dataArray[self.payIndex];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    dic[@"amount"] = money;
    __weak typeof(self) weakSelf = self;
    [BaseNetManager requestWithMethod:POST path:Wallet_charge_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            [weakSelf rechargeData:responseObject[@"data"] type:dic[@"payment"]];
        }else{
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}

- (void)rechargeData:(NSDictionary *)dataDic type:(NSString *)paytype{
    
}

@end
